const state = {
    openedTabs: JSON.parse(localStorage.getItem('openedTabs')) || [] // 初始化时加载 tabs
}

function saveOpenedTabs(tabs) {
    localStorage.setItem('openedTabs', JSON.stringify(tabs));
}

const mutations = {
    addTab(state, tab) {
        if (!state.openedTabs.find(t => t.path === tab.path)) {
            state.openedTabs.push(tab);

        }
    },
    removeTab(state, tabPath) {
        state.openedTabs = state.openedTabs.filter(t => t.path !== tabPath);
    },
    clearTabs(state) {
        state.openedTabs = [];

    },
    setTabs(state, tabs) {
        state.openedTabs = tabs;

    }
}

const actions = {
    addTab({commit, state}, tab) {
        commit('addTab', tab);
        saveOpenedTabs(state.openedTabs);
        // localStorage.setItem('openedTabs', JSON.stringify([...state.openedTabs, tab]));
    },
    removeTab({commit, state}, tabPath) {
        commit('removeTab', tabPath);
        saveOpenedTabs(state.openedTabs);
        // localStorage.setItem('openedTabs', JSON.stringify(this.state.tabs.openedTabs.filter(t => t.path !== tabPath)));
    },
    clearTabs({commit}) {
        commit('clearTabs');
        saveOpenedTabs([]);
    },
    setTabs({commit, state}, tabs) {
        commit('setTabs', tabs);
        saveOpenedTabs(tabs);
    },
    loadTabs({commit}) {
        const tabs = JSON.parse(localStorage.getItem('openedTabs')) || [];
        tabs.forEach(tab => commit('setTabs', tabs));
    }
};
export default {
    namespaced: true,
    state,
    mutations,
    actions
}